package com.hzp.lolnews.ui.novel.view;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hzp.lolnews.R;
import com.hzp.lolnews.base.BaseFragment;
import com.hzp.lolnews.ui.novel.adapter.AutoPlayAdapter;
import com.hzp.lolnews.ui.novel.adapter.NavAdapter;
import com.hzp.lolnews.ui.novel.adapter.NovelAdapter;
import com.hzp.lolnews.ui.novel.bean.AutoPlayBean;
import com.hzp.lolnews.ui.novel.bean.NavBean;
import com.hzp.lolnews.ui.novel.bean.NovelBean;
import com.hzp.lolnews.ui.novel.config.Config;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class NovelFragment extends BaseFragment {


    private ViewPager mVp;
    private RecyclerView oneRecycler;
    private XRecyclerView twoRecycler;
    private LinearLayout ll_points;
    private NavAdapter adapter;
    private NovelAdapter novelAdapter;
    private AutoPlayAdapter mAdapter;

//    public NovelFragment() {
//        // Required empty public constructor
//    }
//
//
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        // Inflate the layout for this fragment
//        return inflater.inflate(R.layout.fragment_novel, container, false);
//    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化控件
        initView(view);
        //首部轮播
        AutoListener();
        //水平recyclerview
        NavListener();
        //垂直recyclerview
        VerListener(false,Config.JSON_VIR_WEN + Config.JSON_REFRESH_WEN);
    }

    private void VerListener(final boolean isMore, final String url) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final rx.Subscriber<? super String> subscriber) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().get().url(url).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String json = response.body().string();
                            if(json.length() > 0){
                                //传递最后的结果
                                subscriber.onNext(json);
                                subscriber.onCompleted();
                            }else{
                                Toast.makeText(getActivity(),"数据为空!",Toast.LENGTH_LONG).show();
                            }
                        }else {
                            subscriber.onError(new Throwable("Error:下载失败..."));
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String data) {
                        try {
                            JSONObject da = new JSONObject(data);
                            JSONObject ob = da.getJSONObject("data");
                            JSONArray array = ob.getJSONArray("rows");
                            Gson gson = new Gson();
                             List<NovelBean> tData;
                            tData = gson.fromJson(array.toString(), new TypeToken<List<NovelBean>>() {
                            }.getType());
                            if (isMore) {
                                novelAdapter.setMoreData(tData);
                            } else {
                                novelAdapter.setData(tData);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        //上下拉刷新
        twoRecycler.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                VerListener(false,Config.JSON_VIR_WEN + Config.JSON_REFRESH_WEN);
                twoRecycler.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                int date = 25;
                if(date > 0){
                    date--;
                    String json = 2016 + "-" + 10 + "-" + date;
                    VerListener(true,Config.JSON_VIR_WEN + json);
                    twoRecycler.loadMoreComplete();
                }else{
                    Toast.makeText(getActivity(),"没有数据了!",Toast.LENGTH_LONG).show();
                }

            }
        });

    }

    //首部轮播
    private void AutoListener() {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final rx.Subscriber<? super String> subscriber) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().get().url(Config.JSON_AUTO_WEN).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String json = response.body().string();
                            if(json.length() > 0){
                                //传递最后的结果
                                subscriber.onNext(json);
                                subscriber.onCompleted();
                            }else{
                                Toast.makeText(getActivity(),"数据为空!",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String data) {
                        try {
                            Gson gson = new Gson();
                            JSONObject obj = new JSONObject(data);
                            JSONObject da = obj.getJSONObject("data");
                            JSONArray auto = da.getJSONArray("rows");
                            final List<AutoPlayBean.DataBean.RowsBean> oData = gson.fromJson(auto.toString(), new TypeToken<List<AutoPlayBean.DataBean.RowsBean>>() {
                            }.getType());
                            mAdapter.setData(oData);
                            for (int i = 0; i <oData.size() ; i++) {
                                View point = new View(getFActivity());
                                DisplayMetrics metrics = new DisplayMetrics();
                                float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 15, metrics);
                                float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 15, metrics);
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) width, (int) height);
                                params.leftMargin = 5;
                                point.setLayoutParams(params);
                                point.setBackgroundResource(R.drawable.normal_points);
                                assert ll_points != null;
                                ll_points.addView(point);
                            }
                            mVp.setCurrentItem(1000);
                            ll_points.getChildAt(0).setBackgroundResource(R.drawable.checked_points);
                            mVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                                @Override
                                public void onPageSelected(final int position) {

                                    for (int i = 0; i < ll_points.getChildCount(); i++) {
                                        ll_points.getChildAt(i).setBackgroundResource(R.drawable.normal_points);
                                        if (i == position % oData.size()) {
                                            ll_points.getChildAt(position % oData.size()).setBackgroundResource(R.drawable.checked_points);
                                        }
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }
    //水平recyclerview
    private void NavListener() {
        //RxJava结合okhttp使用
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final rx.Subscriber<? super String> subscriber) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().get().url(Config.JSON_HOR_WEN).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String json = response.body().string();
                            if(json.length() > 0){
                                //传递最后的结果
                                subscriber.onNext(json);
                                subscriber.onCompleted();
                            }else{
                                Toast.makeText(getActivity(),"数据为空!",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String data) {
                        try {
                            Gson gson = new Gson();
                            JSONObject obj = new JSONObject(data);
                            JSONObject da = obj.getJSONObject("data");
                                JSONArray arr = da.getJSONArray("topic_list");
                                JSONObject array = arr.getJSONObject(0);
                                JSONArray rows = array.getJSONArray("rows");
                                List<NavBean.DataBean.TopicListBean.RowsBean> tData = gson.fromJson(rows.toString(), new TypeToken<List<NavBean.DataBean.TopicListBean.RowsBean>>() {
                                }.getType());
                                adapter.setData(tData);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void initView(View view) {
        mVp = (ViewPager)view.findViewById(R.id.novel_vp);
        oneRecycler = (RecyclerView)view.findViewById(R.id.recycle_one);
        twoRecycler = (XRecyclerView)view.findViewById(R.id.recycler_two);
        ll_points = (LinearLayout)view.findViewById(R.id.ll_points);
        //设置布局管理器
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
        oneRecycler.setLayoutManager(manager);
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        twoRecycler.setLayoutManager(manager1);
        assert mVp != null;
        mAdapter = new AutoPlayAdapter();
        mVp.setAdapter(mAdapter);
        assert oneRecycler != null;
        adapter = new NavAdapter(getActivity());
        oneRecycler.setAdapter(adapter);
        assert twoRecycler != null;
        novelAdapter = new NovelAdapter(getActivity());
        twoRecycler.setAdapter(novelAdapter);
    }

    @Override
    public void initView() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_novel;
    }
}
